<template>
  <div class="video">
    <video ref="videoElement" controls autoplay muted v-if="!error"></video>
    <div class="error" v-else>{{$t('spbfcw')}}</div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import flvjs from "flv.js";
export default {
  name: "flvVideo",
  props: ["height", "destroy"],
  data() {
    return {
      flvPlayer: null,
      error: false
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init(this.url);
    });
  },
  computed: {
    ...mapState("player", ["url"])
  },
  methods: {
    init(url) {
      if (flvjs.isSupported()) {
        this.flvPlayer = flvjs.createPlayer({
          type: "flv",
          isLive: true,
          hasVideo: true,
          url: url,
          enableStashBuffer: false
        });
        console.log("url", url);
        this.flvPlayer.attachMediaElement(this.$refs.videoElement);
        // 加载完成
        this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
          this.error = false;
          this.flvPlayer.play(); // 加载完成后开始播放
          console.log("视频开始播放");
        });
        // 加载失败
        this.flvPlayer.on(flvjs.Events.ERROR, () => {
          this.error = true;
        });

        this.flvPlayer.load(); // 开始加载
      } else {
        this.error = true;
      }
    },
    detachMediaElement() {
      if (this.flvPlayer) {
        this.flvPlayer.pause();
        this.flvPlayer.unload();
        this.flvPlayer.detachMediaElement();
        this.flvPlayer.destroy();
        this.flvPlayer = null;
      }
    }
  },
  watch: {
    url(newRtsUrl) {
      this.error = false;
      this.detachMediaElement();
      this.init(newRtsUrl);
    },
    destroy(newDestroy) {
      if (newDestroy) {
        this.init(this.url);
      } else {
        this.detachMediaElement();
      }
    }
  },
  beforeDestroy() {
    this.detachMediaElement();
  }
};
</script>

<style scoped>
.video {
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
}
video {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
.error {
  position: absolute;
  top: 30%;
  left: 50%;
  margin-left: -120px;
  text-align: center;
  color: #00fdff;
  font-weight: bold;
  font-size: 1.2em;
}
/* 隐藏播放按钮 */
.video-js .vjs-big-play-button {
  display: none !important;
}

/* 隐藏视频时长和其他控件 */
.video-js .vjs-control-bar {
  display: none !important;
}
</style>
